<script setup lang="ts">
import { loginByQQ, bindMobile } from '@/services/user'
import { onMounted, ref } from 'vue'
import { mobileRules, codeRules } from '@/utils/rules'
import { showSuccessToast } from 'vant'
import type { User } from '@/types/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
import { useSendMobileCode } from '@/composable'

const openId = ref('')
const isBind = ref(true) // 是否绑定了手机号

// 1. 三方登录
onMounted(() => {
  // 1.1 验证QQ扫码是否成功
  if (window.QC.Login.check()) {
    window.QC.Login.getMe((id: string) => {
      openId.value = id
      // 1.2 调用自己的三方登录接口
      loginByQQ(id)
        .then((res) => {
          // 登录成功 ---> 存用户信息, 挑战到个人中心
          // console.log(res)
          loginSuccess(res.data)
        })
        .catch(() => {
          // 登录失败 --> 该QQ没有绑定手机号
          isBind.value = false
        })
    })
  }
})

// 2. 绑定手机号
const mobile = ref('')
const code = ref('')
// ---------------- 发送验证码--------------
const { formRef, time, sendCode } = useSendMobileCode(mobile, 'bindMobile')

// ----------------绑定手机号---------------
const onSubmit = async () => {
  const res = await bindMobile({
    mobile: mobile.value,
    code: code.value,
    openId: openId.value
  })
  // ----绑定成功, 意味着登录成功
  loginSuccess(res.data)
}

//------------登录成功后处理----------
const store = useUserStore()
const router = useRouter()
const loginSuccess = (user: User) => {
  store.setUser(user)
  router.push(store.returnUrl || '/user')
  showSuccessToast('登录成功~')
  // 清空仓库的returnUrl的值
  store.setReturnUrl('')
}
</script>

<template>
  <div class="login-page" v-if="!isBind">
    <cp-nav-bar title="QQ登录"></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="formRef" @submit="onSubmit">
      <van-field
        v-model="mobile"
        :rules="mobileRules"
        name="mobile"
        placeholder="请输入手机号"
      ></van-field>
      <van-field
        v-model="code"
        :rules="codeRules"
        name="code"
        placeholder="请输入验证码"
      >
        <template #button>
          <span
            class="btn-send"
            @click="sendCode"
            :class="{ active: time > 0 }"
          >
            {{ time > 0 ? `${time}s后再次发送` : '发送验证码' }}</span
          >
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit">
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
